<?php
namespace app\api\controller\user;

use app\api\controller\Controller;
use app\common\model\user\Grade as GradeModel;
use app\api\model\grade\Order as OrderModel;
use app\api\service\Payment as PaymentService;
use app\common\enum\OrderType as OrderTypeEnum;

class Grade extends Controller {

    public function getChargeGrade(){
        
        $condition['wxapp_id']=$this->wxapp_id;
        $condition['is_free']=1;
        $condition['status']=1;
        $condition['is_delete']=0;
        $d=GradeModel::where($condition)->order('weight desc')->find();
        $data['grade_id']=$d['grade_id'];
        $data['name']=$d['name'];
        $data['amount']=$d['amount'];
        $data['limit_year']=$d['limit_year'];
        $data['points']=$d['points'];

        if($data){
            return $this->renderSuccess($data, '数据获取成功');
        } else {
            return $this->renderError('数据获取失败');
        }

    }

    
    public function submit($grade_id=0){
        // 用户信息
        $userInfo = $this->getUser();
        if(!$grade_id){
            return $this->renderError('未有等级ID参数');
        }
        $condition['grade_id']=$grade_id;
        $amount=GradeModel::where($condition)->value('amount');
        $model = new OrderModel;
        if (!$model->createOrder($userInfo, $grade_id, $amount)) {
            return $this->renderError($model->getError() ?: '购买失败');
        }

        // 构建微信支付
        $payment = PaymentService::wechat(
            $userInfo,
            $model['order_id'],
            $model['order_no'],
            $model['pay_price'],
            OrderTypeEnum::GRADE
        );
        // 充值状态提醒
        //$message = ['success' => '购买成功', 'error' => '订单未支付'];
        return $this->renderSuccess($payment, '支付数据获取成功');

    }

}